import React, { Component } from "react";
import { AgGridReact } from "ag-grid-react";
import "ag-grid-community/dist/styles/ag-grid.css";
import "ag-grid-community/dist/styles/ag-theme-balham.css";
import data from "../../../data/olympicWinners.json";

class GridExample extends Component {
  constructor(props) {
    super(props);

    this.state = {
      columnDefs: [
        {
          headerName: "Athlete",
          field: "athlete",
          minWidth: 150,
        },
        {
          headerName: "Age",
          field: "age",
          minWidth: 50,
        },
        {
          headerName: "Country",
          field: "country",
          minWidth: 120,
        },
        {
          headerName: "Year",
          field: "year",
          minWidth: 90,
        },
        {
          headerName: "Date",
          field: "date",
          minWidth: 110,
        },
        {
          headerName: "Sport",
          field: "sport",
          minWidth: 110,
        },
        {
          headerName: "Gold",
          field: "gold",
          minWidth: 100,
        },
        {
          headerName: "Silver",
          field: "silver",
          minWidth: 100,
        },
        {
          headerName: "Bronze",
          field: "bronze",
          minWidth: 100,
        },
        {
          headerName: "Total",
          field: "total",
          minWidth: 100,
        },
      ],
      rowData: null,
    };
  }

  onGridReady = (params) => {
    this.gridApi = params.api;
    this.gridColumnApi = params.columnApi;
    this.setState({ rowData: data });
  };

  onGridSizeChanged(params) {
    var gridWidth = document.getElementById("grid-wrapper").offsetWidth;
    var columnsToShow = [];
    var columnsToHide = [];
    var totalColsWidth = 0;
    var allColumns = params.columnApi.getAllColumns();
    for (var i = 0; i < allColumns.length; i++) {
      let column = allColumns[i];
      totalColsWidth += column.getMinWidth();
      if (totalColsWidth > gridWidth) {
        columnsToHide.push(column.colId);
      } else {
        columnsToShow.push(column.colId);
      }
    }
    params.columnApi.setColumnsVisible(columnsToShow, true);
    params.columnApi.setColumnsVisible(columnsToHide, false);
    params.api.sizeColumnsToFit();
  }
  render() {
    return (
      <div style={{ width: "100%", height: "100%" }}>
        <div id="grid-wrapper" style={{ width: "100%", height: "100%" }}>
          <div
            id="myGrid"
            style={{
              height: "100%",
              width: "100%",
            }}
            className="ag-theme-balham"
          >
            <AgGridReact
              columnDefs={this.state.columnDefs}
              rowData={this.state.rowData}
              onGridReady={this.onGridReady}
              onGridSizeChanged={this.onGridSizeChanged.bind(this)}
            />
          </div>
        </div>
      </div>
    );
  }
}

export default GridExample;
